#include "type.h"
#include "fifo.h"

bool fifo_init(struct fifo_head *head, fifo_alloc data_alloc,
		fifo_free data_free)
{
	if (!head || !data_alloc || !data_free)
	{
		fprintf (stderr, "FIFO init: NULL parameters\n");
		return false;
	}

	head->head = head->tail = NULL;
	head->data_alloc = data_alloc;
	head->data_free = data_free;
	return true;
}

bool fifo_push(struct fifo_head *head, void *arg)
{
	struct fifo_node *node;

	node = memcalloc(1, sizeof(struct fifo_node));
	if (!node)
	{
		fprintf (stderr, "FIFO insert: allocat memory fail!\n");
		return false;
	}

	node->data = (*head->data_alloc)(arg);

	if (!head->head)
	{
		head->head = head->tail = node;
		return true;
	}
	head->tail->next = node;
	head->tail = node;
	return true;
}

struct fifo_node *fifo_get_first(struct fifo_head *head)
{
	return head->head;
}

void fifo_pop(struct fifo_head *head)
{
	struct fifo_node *first = head->head;

	if (!first)
		return;

	head->head = head->head->next;
	if (head->tail == first)
		head->tail = NULL;
	(*head->data_free)(first->data);
	memfree(first);
}

void fifo_clear(struct fifo_head *head)
{
	while(fifo_get_first(head))
		fifo_pop(head);
}

